package top.tomxwd.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 每个服务调用五次
 *
 * @author xieweidu
 * @createDate 2020-06-14 21:17
 */
public class MyDeptRule extends AbstractLoadBalancerRule {

    /**
     * 调用次数，默认0，如果为5则指向下一个服务【currentIndex+1】
     */
    private AtomicInteger totalCount = new AtomicInteger(0);
    /**
     * 表示第几个服务，默认0，第一个服务被调用
     */
    private AtomicInteger currentIndex = new AtomicInteger(0);

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers(); // 获得活着的服务
            List<Server> allList = lb.getAllServers(); // 获得全部的服务

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }

//            int index = chooseRandomInt(serverCount); // 生成区间随机数
//            server = upList.get(index); // 活着的服务中获取一个

            if (totalCount.get() < 5) {
                server = upList.get(currentIndex.get());
                totalCount.incrementAndGet();
            } else {
                totalCount.set(0);
                int i = currentIndex.incrementAndGet();
                if (i >= upList.size()) {
                    currentIndex.set(0);
                }
                server = upList.get(currentIndex.get());
            }

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            server = null;
            Thread.yield();
        }

        return server;

    }

    /**
     * 生成区间[serverCount]随机数
     *
     * @param serverCount 是全部服务的个数，包括生和死的
     * @return
     */
    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}
